//
//  NetWorkTools.m
//  微博
//
//  Created by 沈艳男 on 15/11/13.
//  Copyright © 2015年 沈艳男. All rights reserved.


#import "NetWorkTools.h"

@protocol NetworkToolsProxy <NSObject>

@optional
// 复制粘贴了 AFN 的内部方法
- (NSURLSessionDataTask *)dataTaskWithHTTPMethod:(NSString *)method
                                       URLString:(NSString *)URLString
                                      parameters:(id)parameters
                                         success:(void (^)(NSURLSessionDataTask *, id))success
                                         failure:(void (^)(NSURLSessionDataTask *, NSError *))failure;

@end

@interface NetWorkTools()<NetworkToolsProxy>

@end

@implementation NetWorkTools

+ (instancetype)sharedNetWorkToosl
{
    static NetWorkTools *instance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        NSURL *baseUrl = [NSURL URLWithString:@""];
        instance = [[self alloc] initWithBaseURL:baseUrl sessionConfiguration:nil];
//        instance.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/plain"];
        instance.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript", @"text/html", @"text/plain", nil];
    });
    return instance;
}

- (void)requset:(RequestMethod)method URLString:(NSString *)urlString parameters:(id)parameters success:(void (^)(id))success error:(void (^)(NSError *e))error
{
    // 判断是什么请求
    NSString *methodName = (method == GET)? @"GET": @"POST";
    [[[NetWorkTools sharedNetWorkToosl] dataTaskWithHTTPMethod:methodName URLString:urlString parameters:parameters success:^(NSURLSessionDataTask * _Nonnull task, id result) {
        if (result) {
            success(result);
        }
    } failure:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nonnull error) {
        if (error) {
            NSLog(@"%@", error);
        }
    }]resume];
}

- (NSURL *)oauthUrl
{
    if (!_oauthUrl) {
        NSURL *oauthUrl = [NSURL URLWithString:[NSString stringWithFormat:@"https://api.weibo.com/oauth2/authorize?client_id=%@&redirect_uri=%@", self.client, self.redirect]];
        _oauthUrl = oauthUrl;
    }
    return _oauthUrl;
}

- (NSString *)client
{
    if (!_client) {
        NSString *client = @"3038223898";
        _client = client;
    }
    
    return _client;
}

- (NSString *)redirect
{
    if (!_redirect) {
        NSString *redirect = @"http://www.baidu.com";
        _redirect = redirect;
    }
    return _redirect;
}

- (NSString *)secret
{
    if (!_secret) {
        NSString *secret = @"424abe4829ab1834808ec6b6183cc1b7";
        _secret = secret;
    }
    return _secret;
}

@end
